﻿using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using MusicFluent.Models;
using MusicFluent.Views;
using NetEasyMusic.Lib.Data;
using NetEasyMusic.Lib.Models;
using NetEasyMusic.Lib.Operations;

namespace MusicFluent.MusicViews;

public partial class PlayMusicView : UserControl
{
    public PlayMusicView(SongModel model, string cookie)
    {
        _model = model;
        _cookie = cookie;
        InitializeComponent();
    }

    private readonly SongModel _model;
    private readonly string _cookie;

    public double Time { get; private set; }

    protected override async void OnInitialized()
    {
        base.OnInitialized();
        using var music = new Music(_cookie);
        var detail = await music.GetSongWithoutCommend(_model);
        PicImage.Source = $"{_model.PicUrl}?param=270y270";
        AlbumBlock.Text = detail.Album;
        SongBlock.Text = detail.Name;
        LyricList.ItemsSource = Music.InitLrc(detail.Lyric);
        Time = int.Parse(_model.Time).ToTime();
    }

    private void LyricClick(object? sender, RoutedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(this);
        if (sender is not Control control) return;
        if (control.DataContext is not KeyValuePair<double, string> keyValuePair) return;
        view?.ChangeTime(keyValuePair.Key / Time);
    }

    public void LyricScroll(double value)
    {
        var list = LyricList.Items.Where(x => x is KeyValuePair<double, string>)
            .Select(x => (x is KeyValuePair<double, string> pair ? pair : default).Key).ToList();
        var result = list.FindIndex(x => Math.Abs(x - value) < 0.565);
        if (result < 0 || result > list.Count) return;
        LyricList.SelectedIndex = result;
    }

    private void AlbumTapped(object? sender, TappedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(Parent as Control);
        if (view == null) return;
        view.TaskShow();
        var artist = new AlbumView(_model.AlbumId);
        view.Navigate(artist);
        view.TaskShow();
    }
}